#include <QGridLayout>
#include <QVBoxLayout>
#include <QButtonGroup>
#include "tictactoe.h"

TicTacToe::TicTacToe(QWidget *parent) :
    QDialog(parent), m_nowCross(true), m_gameFinished(false)
{
    QVBoxLayout *vlay = new QVBoxLayout();
    QGridLayout *grid = new QGridLayout();
    m_label = new QLabel("Tic Tac Toe");
    vlay->addWidget(m_label);
    vlay->addLayout(grid);
    setLayout(vlay);
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            int cur = 3*i + j;
            m_buttons[cur] = new Button(this);
            connect(m_buttons[cur], SIGNAL(clicked()), this, SLOT(onButtonClick()));
            grid->addWidget(m_buttons[cur], i, j);
        }
    }

}

void TicTacToe::onButtonClick()
{
    this->update();
    int sum;
    char owin[] = "O's won!";
    char xwin[] = "X's won!";
    if (!m_gameFinished)
    {
        for (int i = 0; i < 9; ++i)
        {
            m_turns[i] = m_buttons[i]->getState();
        }
        for (int i = 0; i < 3; ++i)
        {
            sum = m_turns[3*i] + m_turns[3*i+1] + m_turns[3*i+2];
            if (sum == 0)
            {
                m_label->setText(owin);
                m_gameFinished = true;
            } else if (sum == 3)
            {
                m_label->setText(xwin);
                m_gameFinished = true;
            }
        }
        for (int i = 0; i < 3; ++i)
        {
            sum = m_turns[i] + m_turns[i+3] + m_turns[i+6];
            if (sum == 0)
            {
                m_label->setText(owin);
                m_gameFinished = true;
            } else if (sum == 3)
            {
                m_label->setText(xwin);
                m_gameFinished = true;
            }
        }
        sum = m_turns[0] + m_turns[4] + m_turns[8];
        if (sum == 0)
        {
            m_label->setText(owin);
            m_gameFinished = true;
        } else if (sum == 3)
        {
            m_label->setText(xwin);
            m_gameFinished = true;
        }
        sum = m_turns[2] + m_turns[4] + m_turns[6];
        if (sum == 0)
        {
            m_label->setText(owin);
            m_gameFinished = true;
        } else if (sum == 3)
        {
            m_label->setText(xwin);
            m_gameFinished = true;
        }
    }
}

